import request from './request'
import { API_BASE_URL, STATIC_BASE_URL } from '@/config';

// 删除本地的 API_BASE_URL 常量
// const API_BASE_URL = 'http://localhost:4000/api';

// 添加处理资源 URL 的工具函数
const getFullResourceUrl = (url: string): string => {
  if (url.startsWith('http')) {
    return url;
  }
  if (url.startsWith('/')) {
    return `${STATIC_BASE_URL}${url}`;
  }
  return `${STATIC_BASE_URL}/${url}`;
};

// 添加类型定义
export interface Song {
  id: string
  title: string
  artist: string
  cover: string
  url: string
  lrc: string
  duration: string
}

export interface PlayList {
  id: string
  name: string
  description: string
  cover: string
  userId: string
  userName: string
  isFavorited: boolean
}

// 添加处理歌单数据的函数
const processPlayListData = (playlist: PlayList): PlayList => {
  if (!playlist) return playlist;
  
  return {
    ...playlist,
    cover: getFullResourceUrl(playlist.cover)  // 处理封面图片路径
  };
};

// 添加处理歌曲数据的函数
const processSongData = (song: Song): Song => {
  if (!song) return song;
  
  return {
    ...song,
    cover: getFullResourceUrl(song.cover),
    url: getFullResourceUrl(song.url),
    lrc: getFullResourceUrl(song.lrc)
  };
};

/**
 * 获取歌单基本信息
 * @param playListId 歌单ID
 * @returns Promise<PlayList>
 * 
 * 预期返回数据格式：
 * {
 *   id: string,          // 歌单ID
 *   name: string,        // 歌单名称
 *   description: string, // 歌单描述
 *   cover: string,       // 歌单封面URL
 *     userId: string,      // 创建者用户ID
 *     userName: string,    // 创建者用户名 
 *   isFavorited: boolean  // 是否被收藏
 * }
 */
export const getPlayListInfo = async (playListId: string): Promise<PlayList> => {
  try {
    const response = await request.get(`/playlist/${playListId}`);
    if (response.data.success && response.data.data) {
      return processPlayListData(response.data.data);
    }
    throw new Error(response.data.message || '获取歌单信息失败');
  } catch (error) {
    console.error('获取歌单基本信息失败:', error);
    throw error;
  }
};

/**
 * 获取整个歌单
 * @param playListId 歌单ID
 * @returns Promise<{ success: boolean, message: string, songs?: Song[] }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 请求是否成功
 *   message: string,  // 提示信息
 *   songs?: Song[]    // 歌曲列表（成功时返回）
 *   每首歌曲的格式为：
 *   {
 *     id: string,          // 歌曲ID
 *     title: string,       // 歌曲标题
 *     artist: string,      // 艺术家
 *     cover: string,       // 歌曲封面URL
 *     url: string,         // 音乐文件URL
 *     lrc: string,         // 歌词文件URL
 *     duration: string     // 音乐时长（秒）
 *   }
 * }
 */
export const getFullPlayList = async (playListId: string): Promise<{ success: boolean, message: string, songs?: Song[] }> => {
  try {
    const response = await request.get(`/playlist/full/${playListId}`);
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message || '获取成功',
        songs: response.data.data.map(processSongData)
      };
    }
    return response.data;
  } catch (error) {
    console.error('获取整个歌单失败:', error);
    return { success: false, message: '获取失败' };
  }
};

/**
 * 获取当前用户创建的所有歌单
 * @returns Promise<{ success: boolean, message: string, playlists?: PlayList[] }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 请求是否成功
 *   message: string,  // 提示信息
 *   playlists?: PlayList[] // 用户的所有歌单列表（成功时返回）
 *   每个歌单的格式为：
 *   {
 *     id: string,          // 歌单ID
 *     name: string,        // 歌单名称
 *     description: string, // 歌单描述
 *     cover: string,       // 歌单封面URL
 *     userId: string,      // 创建者用户ID
 *     userName: string,    // 创建者用户名 
 *     isFavorited: boolean  // 是否被收藏
 *   }
 * }
 */
export const getUserPlaylists = async (): Promise<{ success: boolean, message: string, playlists?: PlayList[] }> => {
  try {
    const response = await request.get(`/user/playlists`);
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message || '获取成功',
        playlists: response.data.data.map(processPlayListData)
      };
    }
    return response.data;
  } catch (error) {
    console.error('获取用户所有歌单失败:', error);
    return { success: false, message: '获取失败' };
  }
};

/**
 * 获取当前用户收藏的所有歌单
 */
export const getFavoritePlaylists = async (): Promise<{ success: boolean, message: string, favoritePlaylists?: PlayList[] }> => {
  try {
    const response = await request.get(`/user/favorites`);
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message || '获取成功',
        favoritePlaylists: response.data.data.map(processPlayListData)
      };
    }
    return response.data;
  } catch (error) {
    console.error('获取用户收藏的歌单失败:', error);
    return { success: false, message: '获取失败' };
  }
};

/**
 * 创建歌单
 */
export const createPlayList = async (data: { 
  name: string; 
  description?: string; 
  coverFile?: File 
}): Promise<{ success: boolean, message: string, playlist?: PlayList }> => {
  try {
    const formData = new FormData();
    formData.append('name', data.name);
    
    if (data.description) {
      formData.append('description', data.description);
    }
    
    if (data.coverFile) {
      formData.append('cover', data.coverFile);
    }

    const response = await request.post(`/playlist/create`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.success && response.data.data) {
      // 处理新的返回格式
      const playlist = response.data.data[0]; // 获取第一个歌单
      return {
        success: true,
        message: response.data.message || '创建成功',
        playlist: processPlayListData(playlist)
      };
    }
    return response.data;
  } catch (error) {
    console.error('创建歌单失败:', error);
    return { success: false, message: '创建失败' };
  }
};

/**
 * 删除歌单
 * @param playListId 歌单ID
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 删除是否成功
 *   message: string   // 提示信息
 * }
 */
export const deletePlayList = async (playListId: string): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.delete(`/playlist/${playListId}`);
    return response.data;
  } catch (error) {
    console.error('删除歌单失败:', error);
    return { success: false, message: '删除失败' };
  }
};

/**
 * 取消收藏歌单
 * @param playListId 歌单ID
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 取消收藏是否成功
 *   message: string   // 提示信息
 * }
 */
export const unfavoritePlayList = async (playListId: string): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.post(`/playlist/${playListId}/unfavorite`);
    return response.data;
  } catch (error) {
    console.error('取消收藏歌单失败:', error);
    return { success: false, message: '取消收藏失败' };
  }
};

/**
 * 获取热门歌单列表
 * @param limit 指定返回的歌单数量
 * @returns Promise<{ success: boolean, message: string, playlists?: PlayList[] }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 请求是否成功
 *   message: string,  // 提示信息
 *   playlists?: PlayList[] // 热门歌单列表（成功时返回）
 *   每个歌单的格式为：
 *   {
 *     id: string,          // 歌单ID
 *     name: string,        // 歌单名称
 *     description: string, // 歌单描述
 *     cover: string,       // 歌单封面URL
 *     userId: string,      // 创建者用户ID
 *     userName: string,    // 创建者用户名 
 *     isFavorited: boolean  // 是否被收藏
 *   }
 * }
 */
export const getHotPlaylists = async (limit?: number): Promise<{ success: boolean, message: string, playlists?: PlayList[] }> => {
  try {
    const response = await request.get(`/playlist/hot`, {
      params: limit ? { limit } : undefined
    });
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message || '获取成功',
        playlists: response.data.data.map(processPlayListData)
      };
    }
    return response.data;
  } catch (error) {
    console.error('获取热门歌单失败:', error);
    return { success: false, message: '获取失败' };
  }
};

/**
 * 收藏歌单
 * @param playListId 歌单ID
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 收藏是否成功
 *   message: string   // 提示信息
 * }
 */
export const favoritePlayList = async (playListId: string): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.post(`/playlist/${playListId}/favorite`);
    return response.data;
  } catch (error) {
    console.error('收藏歌单失败:', error);
    return { success: false, message: '收藏失败' };
  }
};

/**
 * 修改歌单名称
 * @param playListId 歌单ID
 * @param newName 新的歌单名称 (1-50个字符)
 * @returns Promise<{ success: boolean, message: string, playlist?: PlayList }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean,  // 修改是否成功
 *   message: string,   // 提示信息
 *   playlist?: PlayList // 更新后的歌单信息
 * }
 */
export const updatePlayListName = async (
  playListId: string, 
  newName: string
): Promise<{ success: boolean, message: string, playlist?: PlayList }> => {
  try {
    const response = await request.put(`/playlist/${playListId}/name`, { name: newName });
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message,
        playlist: processPlayListData(response.data.data)
      };
    }
    return response.data;
  } catch (error) {
    console.error('修改歌单名称失败:', error);
    return { success: false, message: '修改名称失败' };
  }
};

/**
 * 修改歌单描述
 * @param playListId 歌单ID
 * @param newDescription 新的歌单描述 (最多200个字符)
 * @returns Promise<{ success: boolean, message: string, playlist?: PlayList }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean,  // 修改是否成功
 *   message: string,   // 提示信息
 *   playlist?: PlayList // 更新后的歌单信息
 * }
 */
export const updatePlayListDescription = async (
  playListId: string, 
  newDescription: string
): Promise<{ success: boolean, message: string, playlist?: PlayList }> => {
  try {
    const response = await request.put(`/playlist/${playListId}/description`, { 
      description: newDescription 
    });
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message,
        playlist: processPlayListData(response.data.data)
      };
    }
    return response.data;
  } catch (error) {
    console.error('修改歌单描述失败:', error);
    return { success: false, message: '修改描述失败' };
  }
};

/**
 * 修改歌单封面
 * @param playListId 歌单ID
 * @param coverFile 新的封面图片文件 (支持jpg/png/gif格式，大小不超过2MB)
 * @returns Promise<{ success: boolean, message: string, playlist?: PlayList }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean,  // 修改是否成功
 *   message: string,   // 提示信息
 *   playlist?: PlayList // 更新后的歌单信息
 * }
 */
export const updatePlayListCover = async (
  playListId: string, 
  coverFile: File
): Promise<{ success: boolean, message: string, playlist?: PlayList }> => {
  try {
    const formData = new FormData();
    formData.append('cover', coverFile);

    const response = await request.put(`/playlist/${playListId}/cover`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response.data.success && response.data.data) {
      return {
        success: true,
        message: response.data.message,
        playlist: processPlayListData(response.data.data)
      };
    }
    return response.data;
  } catch (error) {
    console.error('修改歌单封面失败:', error);
    return { success: false, message: '修改封面失败' };
  }
};

/**
 * 添加多首歌曲到多个歌单
 * @param songIds 歌曲ID数组
 * @param playListIds 歌单ID数组
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 添加是否成功
 *   message: string   // 提示信息
 * }
 */
export const addSongsToPlaylists = async (
  songIds: string[],
  playListIds: string[]
): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.post(`/playlist/add-songs`, {
      songIds,
      playListIds
    });
    return response.data;
  } catch (error) {
    console.error('添加歌曲到歌单失败:', error);
    return { success: false, message: '添加失败' };
  }
};

/**
 * 将歌单的所有歌曲添加到播放列表
 * @param playListId 歌单ID
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * 预期返回数据格式：
 * {
 *   success: boolean, // 添加是否成功
 *   message: string   // 提示信息
 * }
 */
export const addPlayListToQueue = async (playListId: string): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.post(`/playlist/${playListId}/add-to-queue`);
    return response.data;
  } catch (error) {
    console.error('添加歌单到播放列表失败:', error);
    return { success: false, message: '添加失败' };
  }
};

/**
 * 从歌单中删除多首歌曲
 * @param playListId 歌单ID
 * @param songIds 要删除的歌曲ID数组
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * 请求方式：DELETE
 * 请求URL：/api/playlist/:playlistId/songs
 * 预期返回数据格式：
 * {
 *   success: boolean, // 删除是否成功
 *   message: string   // 提示信息
 * }
 */
export const removeSongsFromPlaylist = async (
  playListId: string,
  songIds: string[]
): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.delete(`/playlist/${playListId}/songs`, {
      data: { songIds }  // DELETE 请求的请求体需要放在 data 字段中
    });
    return response.data;
  } catch (error) {
    console.error('从歌单删除歌曲失败:', error);
    return { success: false, message: '删除失败' };
  }
};
